'use strict';

const Service = require('egg').Service;
const svgCaptcha = require('svg-captcha');
const md5 = require('md5');
const sd = require('silly-datetime');
const path = require('path');
const mkdirp = require('mz-modules/mkdirp');
const COS = require('cos-nodejs-sdk-v5');
var qr = require('qr-image');

class ToolsService extends Service {
  async getCaptcha() {
    //生成图形验证码
    var captcha = svgCaptcha.create({
      size: 4,
      fontSize: 50,
      width: 120,
      height: 32,
      background: "#cc9966"
    });

    return captcha;
  }
  md5(msg) {
    return md5(msg)
  }
  getUnixTime() {
    let dObj = new Date();
    return Math.ceil(dObj.getTime() / 1000);
  }
  async getUploadFile(filename) {

    //1、获取当前日期 20210920
    let day = sd.format(new Date(), 'YYYYMMDD');

    //2、创建文件保存的路径
    // app/public/upload/20210920
    let dir = path.join(this.config.uploadDir, day);
    await mkdirp(dir);

    //3、生成文件名称  获取文件保存的目录   以前的文件 serverless_600x900.png    20210920.png
    let d = this.getUnixTime();

    //  app/public/upload/20210920/4124215212.png
    let saveDir = path.join(dir, d + path.extname(filename));

    console.log(saveDir);

    return saveDir;
  }
  getFormatTime(){

    let day = sd.format(new Date(), 'YYYY-MM-DD');

    return day;
  }
  getCosUploadFile(filename) {

    //1、获取当前日期 20210920
    let dir = sd.format(new Date(), 'YYYYMMDD');

    //2、生成文件名称  获取文件保存的目录   以前的文件 serverless_600x900.png    20210920.png
    let d = this.getUnixTime();

    //20210412/1618196478.png
    let saveDir = dir + "/" + d + path.extname(filename);
    return saveDir;
  }



  async uploadCos(filename, body) {
    //配置请参考  config/config.default.js
    let cos = new COS({
      SecretId: this.config.cosObject.SecretId,
      SecretKey: this.config.cosObject.SecretKey
    });

    return new Promise((reslove, reject) => {
      cos.putObject({
        Bucket: this.config.cosObject.Bucket, /* 必须 */
        Region: this.config.cosObject.Region,    /* 必须 */
        Key: filename,              /* 必须 */
        StorageClass: 'STANDARD',
        Body: body, // 上传文件对象
        onProgress: function (progressData) {
          console.log(JSON.stringify(progressData));
        }
      }, function (err, data) {
        if (!err) {
          reslove(data)
        } else {
          reject(err);
        }
      });
    })

  }

  async deleteCos(filename) {
    //配置请参考  config/config.default.js
    let cos = new COS({
      SecretId: this.config.cosObject.SecretId,
      SecretKey: this.config.cosObject.SecretKey
    });

    return new Promise((reslove, reject) => {
      cos.deleteObject({
        Bucket: this.config.cosObject.Bucket, /* 必须 */
        Region: this.config.cosObject.Region,    /* 必须 */
        Key: filename       /* 必须 */
      }, function (err, data) {
        if (!err) {
          reslove(data)
        } else {
          reject(err);
        }
      });
    })

  }
  //获取图形二维码
  async getQrImage(qrText) {
    return new Promise((reslove, reject) => {
      try {
        var qrImage = qr.image(qrText, { type: 'png' });
        reslove(qrImage)
      } catch (error) {
        reject(false);
      }

    })
  }
  //获取订单号
  getOrderId() {
    var order_id = sd.format(new Date(), 'YYYYMMDDHHmmss');
    var numArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var randomStr = '';
    for (var i = 0; i < 6; i++) {
      randomStr += numArr[Math.floor(Math.random() * 10)];
    }
    return order_id + randomStr;  /*字符串的拼接*/
  }
  //totalPrice,pMark,tableId,body.orderItems
  getOrderPrintInfo(totalPrice,pMark,tableId,orderItems) {
    var orderInfo;
    orderInfo = "<CB>桌号为" + tableId + "的菜单</CB><BR>";//标题字体如需居中放大,就需要用标签套上
    orderInfo += "名称　　　　　　　<RIGHT>价格　  数量</RIGHT><BR>";
    orderInfo += "--------------------------------<BR>";
    for (var i = 0; i < orderItems.length; i++) {
      orderInfo +=orderItems[i].productTitle.trim() + "　　　　<RIGHT>" + orderItems[i].productPrice + "     " + orderItems[i].productNum + "</RIGHT><BR>";
    }
    orderInfo += "合计：" + totalPrice + "元<BR>";
    orderInfo += "购买时间：" + this.getFormatTime() + "<BR><BR>";
    orderInfo += "备注：<B>" + pMark + "</B><BR><BR>";
    return orderInfo;
  }
}

module.exports = ToolsService;
